<template>
  <div ref="Histogram" :class="className" :style="{ height: height, width: width }" />
</template>

<script setup name="Histogram">
import * as echarts from 'echarts'
import { toRefs } from 'vue'

const Histogram = ref(null)
const animationDuration = ref(3000)

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '500px'
  },
  elementData: {
    type: Object,
    default: undefined
  }
});

const { className, width, height, elementData } = toRefs(props)

watch(elementData, (newValue, oldValue) => {
  initChart()
})

/** 初始化图标 */
function initChart() {
  if (Histogram.value) {
    var myChart = echarts.init(Histogram.value);

    let option = {
      title: {},
      tooltip: {
        trigger: 'axis'
      },
      legend: {},
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category'
      },
      yAxis: {
        type: 'value'
      },
      series: []
    }

    if(elementData.value){
      if(elementData.value.element.titleText){
        option.title.text = elementData.value.element.titleText
      }
      if(elementData.value.element.titleSubtext){
        option.title.subtext = elementData.value.element.titleSubtext
      }
      if(elementData.value.element.titleLeft){
        option.title.left = elementData.value.element.titleLeft
      }
      if(elementData.value.element.tooltip){
        option.tooltip.show = elementData.value.element.tooltip
      }
      if(elementData.value.element.legend){
        option.legend.show = elementData.value.element.legend
      }
      if(elementData.value.element.legendLeft){
        option.legend.left = elementData.value.element.legendLeft
      }
      if(elementData.value.yAxis){
        option.xAxis.data = elementData.value.yAxis
      }
      if(elementData.value.series){
        let series = []
        for(let i = 0; i < elementData.value.series.length; i++){
          series.push({
            name: elementData.value.series[i].name,
            type: 'bar',
            data: elementData.value.series[i].data
          })
        }
        option.series = series
      }
    }

    setTimeout(() => {
      myChart.setOption(option)
      myChart.resize()
    }, 0);
  }
}

initChart();
</script>
